﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class RegisterUI : MonoBehaviour{

	public LoginUI m_LoginUI;

	public InputField m_Phone;
	public InputField m_Password;
	public InputField m_ConfirmPassword;
	public InputField m_UserName;
	public InputField m_Age;
	public Toggle m_Man;
	public Toggle m_WoMan;
	public InputField m_Code;

	private byte m_Sex = 0;

	public Text m_ErrorMsg;

	void Start () {
		gameObject.SetActive(false);
	}

	private void OnEnable()
	{
		Reset();
	}

	private void Reset()
	{
		m_Phone.text = string.Empty;
		m_Password.text = string.Empty;
		m_ConfirmPassword.text = string.Empty;
		m_UserName.text = string.Empty;
		m_Age.text = string.Empty;
		m_Man.isOn = true;
		m_WoMan.isOn = false;
		m_Sex = 0;

		m_ErrorMsg.text = string.Empty;
	}

	public void LoginBtn_Click()
	{
		gameObject.SetActive(false);
		m_LoginUI.gameObject.SetActive(true);
	}

	public void RegisterBtn_Click()
	{
		if (string.IsNullOrEmpty(m_Phone.text))
		{
			m_ErrorMsg.text = "请输入手机号";
			return;
		}

		if (m_Phone.text.Length != 11)
		{
			m_ErrorMsg.text = "手机号格式不正确";
			return;
		}

		if (string.IsNullOrEmpty(m_Password.text))
		{
			m_ErrorMsg.text = "请输入密码";
			return;
		}

		if (m_Password.text.Length < 4 || m_Password.text.Length > 10)
		{
			m_ErrorMsg.text = "密码不的小于4位，不得大于10位";
			return;
		}

		if (m_Password.text != m_ConfirmPassword.text)
		{
			m_Password.text = string.Empty;
			m_ConfirmPassword.text = string.Empty;
			m_ErrorMsg.text = "密码不一致，请重新输入";
			return;
		}

		if (string.IsNullOrEmpty(m_UserName.text))
		{
			m_ErrorMsg.text = "请输入姓名";
			return;
		}

		if (m_UserName.text.Length > 10)
		{
			m_ErrorMsg.text = "姓名不得大于10位";
			return;
		}

		if (string.IsNullOrEmpty(m_Age.text))
		{
			m_ErrorMsg.text = "请输入年龄";
			return;
		}

		AccountInfo accountInfo = new AccountInfo();
		accountInfo.Phone = m_Phone.text;
		accountInfo.Password = m_Password.text;
		accountInfo.UserName = m_UserName.text;
		accountInfo.Age = string.IsNullOrEmpty(m_Age.text) ? 0 : int.Parse(m_Age.text);
		accountInfo.Sex = m_Sex;

		StartCoroutine(Request.RegisterAccount(accountInfo, errorCode => {
			if (errorCode != ErrorCode.Success)
			{
				m_ErrorMsg.text = errorCode == ErrorCode.Fail ? "注册失败，请重试" : ErrorMsg.Instance.GetMsg(errorCode);
			}
			else
			{
				m_ErrorMsg.text = "注册成功，转到登录界面...";
				StartCoroutine(ToLoginUI());
			}
		}));
	}

	public IEnumerator ToLoginUI()
	{
		yield return new WaitForSeconds(1);

		LoginBtn_Click();
	}

	public void ManCtl_Click()
	{
		m_Sex = 0;
	}

	public void WomanCtl_Click()
	{
		m_Sex = 1;
	}

	public void SendBtn_Click()
	{
		
	}
}
